<?php

namespace Xrfg\Api\Trading\Account\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Xrfg\Core\Trading\Account\Models\Address;
use Xrfg\Core\Trading\Account\Models\Coin;
use Xrfg\Api\Trading\Account\Requests\AddAddressRequest;
use Xrfg\Api\Trading\Account\Resources\AddressResource;

class AddressController extends Controller
{
    /**
     * 地址列表.
     *
     * @param Coin $coin
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Coin $coin)
    {
        $address = Address::select(['id', 'coin_id', 'address', 'note', 'tag', 'is_usdt_erc20'])
            ->when($coin->exists, function (Builder $query) use ($coin) {
                return $query->where('coin_id', $coin->id);
            })
            ->where('user_id', Auth::id())
            ->orderByDesc('id')
            ->get();

        return AddressResource::collection($address);
    }

    /**
     * 添加地址.
     *
     * @param AddAddressRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(AddAddressRequest $request)
    {
        $address = new Address();
        $address->user_id = Auth::id();
        $address->address = $request->input('address');
        $address->coin_id = $request->input('coin_id');
        $address->note = $request->input('note');
        $address->tag = $request->input('tag');
        if ('ERC20' == $request->input('chain_name')) {
            $address->is_usdt_erc20 = 1;
        }
        $address->save();

        return $this->null();
    }

    /**
     * 删除地址.
     *
     * @param Address $address
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Exception
     */
    public function destroy(Address $address)
    {
        $address->delete();

        return $this->null();
    }
}
